<?php

class UsersController extends MController {

    public function loginAction() {
        $postDatas = $this->getRequest()->getPost();
        $errors = new MError();

        if( $this->getRequest()->isPost() ) {

            // Test the inputs
            $inputs = array('username', 'password');
            $flagInputs = true ;
            foreach( $inputs as $input ) {
                if( (!isset($postDatas[$input])) || ($postDatas[$input] == NULL) )
                    $flagInputs = false;
            }


            // Make the login
            if( $flagInputs ) {
                if( MSession::getInstance()->login(MSession::NORMAL_AUTH, $postDatas['username'], $postDatas['password']) ) {
                    __redirect(__route('ml-forum/'));
                } else {
                    $errors->addError('Connection failed...');
                }
            } else {
                $errors->addError('All the form must be completed');
            }
        }
        
        // Render the login page
        $this->render('login', array('errors' => $errors));

    }


    public function logoutAction() {
        MSession::getInstance()->logout();
        __redirect(__route('ml-forum/'));
    }



    public function registerAction() {
        $postDatas = $this->getRequest()->getPost();
        $errors = new MError();

        if( $this->getRequest()->isPost() ) {

            // Test the inputs
            $inputs = array('username', 'password', 'confirmPassword', 'email');
            $flagInputs = true ;
            foreach( $inputs as $input ) {
                if( (!isset($postDatas[$input])) || ($postDatas[$input] == NULL) )
                    $flagInputs = false;
            }

            // Make the registration
            if( $flagInputs ) {
                $registration = MSession::getInstance()->register( $postDatas['username'], $postDatas['password'], $postDatas['email']);
                if( $registration === MSession::REGISTER_SUCCESS ) {
                    __redirect(__route('ml-forum/home'));
                } else if( $registration === MSession::REGISTER_USER_EXIST ){
                    $errors->addError('This user already exists.');
                }
            } else {
                $errors->addError('All the form must be completed.');
            }

            // Render the error(s)
            if( $errors->hasErrors() ) {
                $this->render('register', array('errors' => $errors));
            }
        } else {
            $this->render('register', array('errors' => $errors));
        }

    }


}

?>